import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PubSub from "pubsub-js";
import { ListView, Toast, SwipeAction, ActivityIndicator,Modal,Button } from 'antd-mobile';
import { animateScroll as scroll } from "react-scroll";
import { setDocumentTitle, getCategoryAudios, removeAudio, removeStoreCategory } from '../utils';
import AudioItem from '../components/AudioItem';
import '../css/nas.css';

/**
 * 我的收藏类别
 */
const alert = Modal.alert;
class MyStoreCategorys extends Component {
    constructor(props, context) {
        super(props, context);

        this.handleSwipeCancel = this.handleSwipeCancel.bind(this);
        this.scroll = this.scroll.bind(this);
        this.handleRemotePlay = this.handleRemotePlay.bind(this);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        // 类别
        let category = this.props.location.category;
        if (category) {
            sessionStorage.setItem('temp_category', JSON.stringify(category));
        } else {
            category = JSON.parse(sessionStorage.getItem('temp_category'));
        }
        this.state = {
            audioList: [],
            dataSource: ds.cloneWithRows([]),
            height: document.documentElement.clientHeight * 3,
            hasMore: true,
            isLoading: true,
            latestId: 0,
            category: category,
            animating: false,
            hiddenBack: true,
            count: category.count || 0
        }
        this.startTime = 0;
    }

    componentDidMount() {
        setDocumentTitle(this.state.category.title);
        this._mounted = true;
        const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
        this.setState({
            height: hei,
        });
        this.loadFavorite();
        window.addEventListener("scroll", this.scroll);
    }

    componentWillUnmount() {
        this._mounted = false;
        window.removeEventListener("scroll", this.scroll);
    }

    handleScrollTo() {
        this.scrollToTop();
    }
    // 清除全部
    handleClearAll() {
        if (this.state.count === 0) {
            Toast.show('还未添加收藏', 1, false);
            return;
        }
        const message = '确定移除所有的音频?';
        this.alert = alert('', message,
            [
                { text: '取消' },
                {
                    text: '确定', onPress: () =>
                        this.clearAllAudio()
                },
            ]);
    }

    async clearAllAudio() {
        const data = await removeStoreCategory(this.state.category.category_id);
        if (data.errcode === 0) {
            Toast.show('删除成功', 1, false);
            // 更新对应的uid, 显示个数以及删除按钮置灰
            const ds = new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            });
            this.setState({
                audioList: [],
                dataSource: ds.cloneWithRows([]),
                isLoading: false,
                hasMore: false,
                count: 0
            });
        } else {
            Toast.show('删除失败', 1, false);
        }
    }

    // 滑动事件监听
    scroll(event) {
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop >= 180) {
            if (this.state.hiddenBack) {
                this.setState({ hiddenBack: false });
            }
        } else if (scrollTop <= 180 && !this.state.hiddenBack) {
            this.setState({ hiddenBack: true });
        }
    }

    scrollToTop() {
        scroll.scrollToTop({ duration: 200 });
    }

    // 点播
    handleRemotePlay(audio) {
        PubSub.publish('remotePlay', { category_id: this.state.category.category_id, audio: audio, audioList: this.state.audioList });
    }

    eventDispatch() {
        const end = new Date().getTime();
        if (end - this.startTime <= 200) {
            this.startTime = end;
            return true;
        }
        this.startTime = end;
        return false;
    }

    // 滑动取消收藏
    handleSwipeCancel(audio, index) {
        this.setState({
            animating: true
        });
        removeAudio(audio.audio_id, this.state.category.category_id,(result) => {
            this.setState({
                animating: false
            });
            if (result.errcode === 0) {
                this.updateAudioList(index);
                Toast.show('移除成功', 1, false);
            } else {
                Toast.show('移除失败', 1, false);
            }
        });
    }

    // 更新数据
    updateAudioList(index) {
        let newAudioList = this.state.audioList;
        newAudioList.splice(index, 1);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        })
        const count = this.state.count -1;
        this.setState({
            count:count,
            audioList: newAudioList,
            dataSource: ds.cloneWithRows(newAudioList),
        });
    }

    // 加载最爱列表数据
    async loadFavorite() {
        const result = await getCategoryAudios(this.state.category.category_id, this.state.latestId);
        if (!this._mounted) {
            return;
        }
        // 获取失败
        if (result.errcode !== 0) {
            this.setState({ isLoading: false, });
            return;
        }
        const count = result.data.length;
        // 没有发现有更多数据
        if (count === 0) {
            this.setState({ isLoading: false, hasMore: false });
            return;
        }

        let newAudioList = this.state.audioList.concat(result.data);
        newAudioList = newAudioList.map((item) => {
            return Object.assign(item,{store_category_id:this.state.category.category_id});
        })
        const latestId = result.data[count - 1].id;
        this.setState({
            audioList: newAudioList,
            dataSource: this.state.dataSource.cloneWithRows(newAudioList),
            isLoading: false,
            hasMore: count >= 20,
            latestId: latestId
        });
    }

    // 上拉加载更多
    onEndReached = (event) => {
        if (this.eventDispatch()) {
            return;
        }
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        this.loadFavorite();
    }

    render() {
        return (
            <div style={{ width: '100%', height: '100%' }}>
                <div style={{ height: "96px", width: "100%", display: "flex", justifyContent: "center", alignItems: "center" }}>
                    <img src={this.state.category.url} style={{ height: "48px", width: "48px", borderRadius: "6px" }} alt="" />
                </div>
                <div style={{ height: "42px", width: "100%", display: "flex", background: 'white' }}>
                    <div style={{ width: "100%", height: "46px" }}>
                        <p style={{ marginTop: "13px", marginLeft: "10px", color: "#616161" }}>曲目({this.state.count})</p>
                    </div>
                    <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "46px", position: "none" }}>
                        <Button inline size="small" style={{ marginRight: "6px", marginBottom: "2px", fontSize: "12px", color: "#9E9E9E" }}
                            onClick={this.handleClearAll.bind(this)}>移除全部</Button>
                    </div>
                </div>

                <div style={{ paddingBottom: "0px", background: "#f5f5f9" }}>
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderFooter={() => (
                            <div style={{
                                padding: "16px",
                                textAlign: 'center',
                                fontSize: '13px',
                            }}>
                                {this.state.hasMore ? "正在加载内容..." : '没有更多内容了~'}
                            </div>)}
                        renderRow={(rowData, sectionID, rowID) => {
                            return (
                                <SwipeAction
                                    key={"" + rowID}
                                    autoClose
                                    right={[
                                        {
                                            text: '删除',
                                            onPress: () => this.handleSwipeCancel(rowData, parseInt(rowID, 10)),
                                            style: { background: '#F4333C', color: 'white', width: "56px" },
                                        },
                                    ]}
                                >
                                    <AudioItem
                                        audio={rowData}
                                        categoryId={this.state.category.category_id}
                                        hiddenRight={true}
                                        index={parseInt(rowID, 10)}
                                        handleRemotePlay={this.handleRemotePlay} />
                                </SwipeAction>
                            );
                        }}
                        initialListSize={2000}
                        pageSize={1}
                        useBodyScroll={true}
                        className="am-list"
                        scrollEventThrottle={100}
                        scrollRenderAheadDistance={300}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={20}
                    />

                </div>
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={this.state.animating}
                />
                <div style={{
                    position: "fixed",
                    display: "flex",
                    textAlign: "center",
                    justifyContent: "center",
                    top: "20px",
                    right: "20px",
                    width: "25px",
                    height: "25px",
                    marginLeft: this.left,
                    backgroundColor: "#424242",
                    opacity: 0.7,
                    borderRadius: "5px",
                    color: "#ffffff",
                    fontSize: "11px",
                    padding: "7px",
                    visibility: this.state.hiddenBack ? "hidden" : "visible",
                    lineHeight: 1.2,
                    zIndex: 10,
                }} onClick={this.handleScrollTo.bind(this)}>
                    <span>返回顶部</span>
                </div>
            </div>
        )
    }
}

export default MyStoreCategorys;